import 'package:dio/dio.dart';
import 'package:enjoy_plus_bryant/utils/eventbus.dart';
import 'package:enjoy_plus_bryant/utils/http.dart';
import 'package:enjoy_plus_bryant/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {'id': '', 'avatar': null, 'nickName': null};
  // 控制器定义输入框文本
  final TextEditingController _nickNameController = TextEditingController();
  @override
  void initState() {
    super.initState();
    print(widget.userInfo);
    setState(() {
      userInfo = widget.userInfo;
      // 赋值输入框
      _nickNameController.text = userInfo['nickName'] ?? '';
    });
  }

  // 修改呢称
  void editNickName() async {
    // 1. 获取输入框文字
    String nickName = _nickNameController.text;
    // 2. 呢称不能为空提示
    if (nickName.isEmpty) {
      return ToastUtil.showError('呢称不能为空');
    }
    // 3. 呢称不能超过10个字
    if (nickName.length > 10) {
      return ToastUtil.showError('呢称不能超过10个字');
    }
    // 4.呢称重复
    if (nickName == userInfo['nickName']) {
      return ToastUtil.showError('呢称不能重复');
    }
    // 5. 发送请求修改呢称
    try {
      await http.put('/userInfo', data: {'nickName': nickName});
      ToastUtil.showSuccess('修改成功');
    } catch (e) {
      ToastUtil.showError('修改失败');
    }
  }

  // 展示弹窗
  void onShowSheet() async {
    // 1. 展示弹窗
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          height: 150,
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                trailing: Icon(Icons.arrow_right),

                title: const Text('拍照'),
                onTap: () {
                  // print('点击拍照');
                  selectType('camera');
                },
              ),
              ListTile(
                leading: const Icon(Icons.image),
                trailing: Icon(Icons.arrow_right),
                title: const Text('相册'),
                onTap: () {
                  // print('点击相册');
                  selectType('gallery');
                },
              ),
            ],
          ),
        );
      },
    );
  }

  // 选择图片上传形式 - 相机或相册
  void selectType(String imageType) async {
    // 1. 创建图片选择器
    ImagePicker picker = ImagePicker();
    // 2. 判断是拍照还是相册
    if (imageType == 'camera') {
      // 选择拍照 - 调用相机
      final XFile? image = await picker.pickImage(source: ImageSource.camera);
      if (image != null) {
        uploadAvatar(image.path);
      }
      // ToastUtil.showSuccess('拍照');
    } else if (imageType == 'gallery') {
      // 选择相册
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        uploadAvatar(image.path);
      }
      // ToastUtil.showSuccess('相册');
    }
  }

  // 上传头像请求
  uploadAvatar(String path) async {
    // ToastUtil.showSuccess(path);
    // 1. 包装formData对象， 接口需要
    FormData fd = FormData.fromMap({
      "file": await MultipartFile.fromFile(path),
      "type": "avatar",
    });
    // 2. 发送请求 - 修改一下post请求
    try {
      var res = await http.post('/upload', data: fd);
      // print(res);
      if (res['code'] != 10000) return ToastUtil.showError('上传失败');
      ToastUtil.showSuccess('上传成功');
      // 渲染头像
      setState(() {
        userInfo['avatar'] = res['data']['url'];
      });
    } catch (e) {
      ToastUtil.showError('上传失败');
    } finally {
      // 关闭弹窗
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        // 返回
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
            //
            eventBus.fire(
              RefreshNickname(_nickNameController.text, userInfo['avatar']),
            );
          },
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        onShowSheet();
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: userInfo['avatar'] == null
                            ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 30,
                                height: 30,
                              )
                            : Image.network(
                                userInfo['avatar'],
                                width: 30,
                                height: 30,
                              ),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12),
                  ],
                ),
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                  // 输入内容结束
                  onEditingComplete: () {
                    // print('输入完成');
                    editNickName();
                  },
                  // 失去焦点
                  // onTapOutside: (event) {
                  //   // print('失去焦点');
                  //   editNickName();
                  // },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12),
            ],
          ),
        ],
      ),
    );
  }
}
